package com.itheima.sh.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component //注册到容器
@Order(-1)  //参数越小 越先拦截
public class loginFilter implements GlobalFilter {
    /*
    * 模拟用户登录 判断浏览器访问 是否携带 username=hwl
    * 如果携带则放行 不携带 则拦截
    * */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1 得到 request 对象
        ServerHttpRequest request = exchange.getRequest();

        // 2 从request获取请求参数 token
        String token = request.getQueryParams().getFirst("user");

        // 3 判断access-token值是否为admin
        if (!"hwl".equals(token)) {  // 拦截
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        // 放行
        return chain.filter(exchange);
    }
}
